/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import ContentManagers.Models.Customer;
import ContentManagers.RoleManagers.CustomerManager;
import ContentManagers.Security.Encryptor;
import ContentManagers.Security.Hasher;
import ContentManagers.Security.Validator;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Martin San Diego
 */
public class ServletRegister extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
        
            Customer newCustomer = new Customer();
            boolean check, result = false;
            String tempPassword[] = new String[2];
            
            //check if a similar username already exists in the database
            check = new CustomerManager().checkIfExisting(request.getParameter("newUsername"));
            
            if(check == false)
                {   
                    //store user input to class variables
                    newCustomer.setUsername(Validator.inputSanitizer(request.getParameter("newUsername")));
                    newCustomer.setLastName(Validator.inputSanitizer(request.getParameter("newUserLastName")));
                    newCustomer.setFirstName(Validator.inputSanitizer(request.getParameter("newUserFirstName")));
                    newCustomer.setMiddleInitial(Validator.inputSanitizer(request.getParameter("newUserMiddleName")));

                    //process password here
                    tempPassword = Hasher.processPassword(Validator.passwordSanitizer(request.getParameter("newPassword")));


                    newCustomer.setPassword(tempPassword[0]);
                    newCustomer.setPasswordSalt(tempPassword[1]);
                    newCustomer.setEmail(Validator.inputSanitizer(request.getParameter("newEmail")));
                    newCustomer.setBillingHouseNo(Validator.inputSanitizer(request.getParameter("billingHouseNumber")));
                    newCustomer.setBillingStreet(Validator.inputSanitizer(request.getParameter("billingStreet")));
                    newCustomer.setBillingSubdivision(Validator.inputSanitizer(request.getParameter("billingSubdivision")));
                    newCustomer.setBillingCity(Validator.inputSanitizer(request.getParameter("billingCity")));
                    newCustomer.setBillingPostalCode(Validator.inputSanitizer(request.getParameter("billingPostalCode")));
                    newCustomer.setBillingCountry(Validator.inputSanitizer(request.getParameter("billingCountry")));

                    newCustomer.setDeliveryHouseNo(Validator.inputSanitizer(request.getParameter("deliveryHouseNumber")));
                    newCustomer.setDeliveryStreet(Validator.inputSanitizer(request.getParameter("deliveryStreet")));
                    newCustomer.setDeliverySubdivision(Validator.inputSanitizer(request.getParameter("deliverySubdivision")));
                    newCustomer.setDeliveryCity(Validator.inputSanitizer(request.getParameter("deliveryCity")));
                    newCustomer.setDeliveryPostalCode(Validator.inputSanitizer(request.getParameter("deliveryPostalCode")));
                    newCustomer.setDeliveryCountry(Validator.inputSanitizer(request.getParameter("deliveryCountry")));
                    try {
                        newCustomer.setCreditCardName(Encryptor.encrypt(Validator.inputSanitizer(request.getParameter("creditName"))));        
                        newCustomer.setCreditCardNo(Encryptor.encrypt(Validator.inputSanitizer(request.getParameter("creditCardNo"))));
                        newCustomer.setCreditCardType(Encryptor.encrypt(Validator.inputSanitizer(request.getParameter("creditCardType"))));
                        newCustomer.setExpirationDate(Encryptor.encrypt(Validator.inputSanitizer(request.getParameter("creditExpiryDate"))));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                     }

                    try {
                        result = new CustomerManager().addCostumer(newCustomer);

                    }catch(Exception e){e.printStackTrace();}
                    if(result == true)
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+newCustomer.getUsername()+" registration successful.",true);
                        response.sendRedirect("index.jsp"); 
                    }
                    else
                    {
                        WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+newCustomer.getUsername()+" registration failed.",false);
                        HttpSession session = request.getSession();
                        session.setAttribute("errorMessage", "2");
                        response.sendRedirect("index_new_user.jsp"); 
                    }
                }
            else
            {
                WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+newCustomer.getUsername()+" registration failed.",true);
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", "1");
                response.sendRedirect("index_new_user.jsp"); 
            }
            
    }
    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
